#include "FileSystem.h"

namespace Stray {
namespace Core {

bool createDir(const Path& path)
{
	boost::system::error_code ec;
	return boost::filesystem::create_directory(path, ec);
}

Path getCurrentDir()
{
	return boost::filesystem::current_path();
}

void setCurrentDir(const Path& path)
{
	boost::system::error_code ec;
	boost::filesystem::current_path(path, ec);
}

Path abusolute(const Path& path, const Path& base)
{
	return boost::filesystem::absolute(path, base);
}

Path relative(const Path& path, const Path& base)
{
	boost::filesystem::path fromPath, fromBase, output;

	if(path.is_relative()) abusolute(path);
	if(base.is_relative()) abusolute(base);

	boost::filesystem::path::const_iterator pathIter = path.begin(), pathEnd = path.end();
	boost::filesystem::path::const_iterator baseIter = base.begin(), baseEnd = base.end();

	//Path 

	if((pathIter == pathEnd)||(baseIter == baseEnd)) return path;

#ifdef _WIN32
	if(*pathIter != *baseIter) return path;

	++pathIter, ++baseIter;
#endif

	const std::string dot(".");
	const std::string dots("..");
#ifdef _WIN32
	const std::string sep("\\");
#else
	const std::string sep("/");
#endif

	while(true)
	{
		if((pathIter == pathEnd) || (baseIter == baseEnd) || (*pathIter != *baseIter))
		{
			std::cout << pathIter->string().c_str() << " : " << baseIter->string().c_str() << std::endl;
			for(; baseIter != baseEnd; ++baseIter)
			{
				if(*baseIter == dot) continue;
				else if(*baseIter == sep) continue;

				output /= dots + sep;
			}

			boost::filesystem::path::iterator pathIterStart = pathIter;
			for(; pathIter != pathEnd; ++pathIter)
			{
				if(pathIter != pathIterStart)
					output /= sep;

				if(*pathIter == dot)
					continue;

				if(*pathIter == sep)
					continue;

				output /= *pathIter;
			}

			break;
		}

		fromPath /= boost::filesystem::path(*pathIter);
		fromBase /= boost::filesystem::path(*baseIter);

		++pathIter, ++baseIter;
	}

	return output;
}

}
}